package com.platform.modules.wallet.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.platform.common.exception.BaseException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class VerifyFaceUtil extends AppCode {

    public static boolean
    verify(String name, String idcard, String imagesUrl) {
        String host = "https://jmfaceid.market.alicloudapi.com";
        String path = "/idcard-face/validate";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
//        bodys.put("facePhotoBase64", "facePhotoBase64");
        bodys.put("facePhotoUrl", imagesUrl);
        bodys.put("idCardNo", idcard);
        bodys.put("name", name);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //{"data":{"order_no":"750618183538189226","score":0.95,"msg":"系统判断为同一人","incorrect":100,"sex":"男","birthday":"19880101","address":"浙江省台州地区仙居县"},"msg":"成功","success":true,"code":200,"taskNo":"28802774411472807931"}
            //{"data":{"order_no":"070505199731068287","msg":"照片质量不合格","incorrect":107,"sex":"男","birthday":"19880101","address":"浙江省台州地区仙居县"},"msg":"成功","success":true,"code":200,"taskNo":"50908366984274624977"}
            String s = EntityUtils.toString(response.getEntity());
            System.out.println(s);
            JSONObject jsonObject = JSONUtil.parseObj(s).getJSONObject("data");

            if (jsonObject.getInt("incorrect") == 100) {
                return true;
            }

            throw new BaseException("人脸认证失败：" + jsonObject.getStr("msg"));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

}
